﻿using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Lswweb.Model;
using Lswweb.IDAL;

namespace Lswweb.SqlServerDAL
{
    public class SiteSettingsDAL : ISiteSettings
    {
        private string select = "select Settings from SiteSettings where SettingId=@SettingId and Ver=@Ver;";
        private string insert = "insert into SiteSettings(SettingId,Settings,Ver) values(@SettingId,@Settings,@Ver)";
        private string delete = "delete from SiteSettings where SettingId=@SettingId and Ver=@Ver;";

        public Hashtable GetSettings(int settingId,string ver)
        {
            Hashtable ht = new Hashtable();
            
            using(IDataReader read = DataAccess.ExecuteReader(select, DataAccess.CreateParameter("@SettingId",settingId),DataAccess.CreateParameter("@Ver",ver))){
                if (read.Read())
                    ht = ConvertToHashtable((Byte[])read["Settings"]);
                read.Close(); 
            }
    
            return ht;
        }

        public void Insert(int settingId,Hashtable settings,string ver)
        {
            DataAccess.ExecuteNonQuery(delete, DataAccess.CreateParameter("@SettingId",settingId),DataAccess.CreateParameter("@Ver",ver));

            IDataParameter[] parameters = new IDataParameter[3];
            parameters[0] = DataAccess.CreateParameter("@SettingId", settingId);
            parameters[1] = DataAccess.CreateParameter("@Settings", ConvertToByte(settings));
            parameters[2] = DataAccess.CreateParameter("@Ver",ver);
            
            DataAccess.ExecuteNonQuery(insert, parameters);
        }

        private Byte[] ConvertToByte(Hashtable settings)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            Byte[] b;

            binaryFormatter.Serialize(memoryStream, settings);
            memoryStream.Position = 0;
            b = new Byte[memoryStream.Length];
            memoryStream.Read(b, 0, b.Length);
            memoryStream.Close();
            memoryStream.Dispose();
      
            return b;
        }

        private Hashtable ConvertToHashtable(Byte[] b)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            Byte[] b1=b;
            Hashtable ht=new Hashtable();

            memoryStream.Write(b1,0,b1.Length);
            memoryStream.Position = 0;
            ht=(Hashtable)binaryFormatter.Deserialize(memoryStream);
            memoryStream.Close();
            memoryStream.Dispose();

            return ht;
        }
    }
}
